package best.driver.android.View;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import best.driver.android.AppInfo;
import best.driver.android.Beans.OrderStatus;
import best.driver.android.BestApp;

import best.driver.android.R;
import best.driver.android.Utils.Logger;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.*;

import java.util.ArrayList;
import java.util.List;


public class BestMapView extends RelativeLayout implements BaiduMap.OnMapClickListener,
        OnGetRoutePlanResultListener, View.OnTouchListener {
    protected Context mContext;
    int nodeIndex = -1;//节点索引,供浏览节点时使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;
    private TextView popupText = null;//泡泡view
    private String type;
    private List<LatLng> passPoints;

    //地图相关，使用继承MapView的MyRouteMapView目的是重写touch事件实现泡泡处理
    //如果不处理touch事件，则无需继承，直接使用MapView即可
    MapView mMapView = null;    // 地图View
    public BaiduMap mBaiduMap = null;
    TextView mTvDistance;
    LinearLayout mLLDistance;
    //搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用

    public BestMapView(Context context) {
        super(context);
        mContext = context;
        initView();
        initMapViewSettings();
    }

    public BestMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }

    public BestMapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    private void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.view_best_mapview, this);
        mMapView = (MapView) findViewById(R.id.map_view);
        mBaiduMap = mMapView.getMap();
        mMapView.setOnTouchListener(this);
        mLLDistance = (LinearLayout) findViewById(R.id.ll_distance);
        mTvDistance = (TextView) findViewById(R.id.tv_distance);
        initMapViewSettings();
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);

    }

    public void setCenter(LatLng latLng) {
        MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(latLng);
        mMapView.getMap().animateMapStatus(status);
    }

    public void setDistance(double distance) {
        mTvDistance.setText(distance + "");
    }

    public void showDistance() {
        mLLDistance.setVisibility(View.VISIBLE);
    }

    public void hideDistance() {
        mLLDistance.setVisibility(View.GONE);
    }



    private void initMapViewSettings() {
        float zoomLevel = 17;
        MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(zoomLevel);
        mBaiduMap.animateMapStatus(u);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }


    public void planRoute(LatLng driverStart, LatLng driverEnd, LatLng customerStart, LatLng customerEnd, String startAddress, String endAddress) {

        if (customerStart != null && customerEnd != null) {
            PlanNode stNode = PlanNode.withLocation(customerStart);
            PlanNode edNode = PlanNode.withLocation(customerEnd);

            mSearch.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(edNode));
        }
    }

    public void planRoute(LatLng customerStart, LatLng customerEnd, List<LatLng> passPoints, String type) {

        this.type = type;
        this.passPoints = passPoints;
        if(customerStart != null && customerEnd != null) {
            PlanNode stNode = PlanNode.withLocation(customerStart);
            PlanNode edNode = PlanNode.withLocation(customerEnd);
            DrivingRoutePlanOption option = new DrivingRoutePlanOption().from(stNode).to(edNode);
            List<PlanNode> passNotes = new ArrayList<PlanNode>();
            for(int i = 0; i < passPoints.size(); i++) {
                passNotes.add(PlanNode.withLocation(passPoints.get(i)));
            }
            if(passNotes.size() > 0) {
                option.passBy(passNotes);
            }
            mSearch.drivingSearch(option);

        }
    }

    public void planRoute(List<LatLng> passPoints) {
        if(passPoints != null && passPoints.size() >= 2) {
            List<PlanNode> passNotes = new ArrayList<PlanNode>();
            for(int i = 0; i < passPoints.size(); i++) {
                passNotes.add(PlanNode.withLocation(passPoints.get(i)));
            }
            mSearch.drivingSearch(new DrivingRoutePlanOption().passBy(passNotes));
        }
    }

    @Override
    public void onMapClick(com.baidu.mapapi.model.LatLng point) {
        mBaiduMap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi poi) {
        return false;
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult result) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult result) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(BestApp.getInstance().getApplicationContext(), "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            Logger.d("bestMap", result.toString());
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            //result.getSuggestAddrInfo()
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            route = result.getRouteLines().get(0);
            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);
            routeOverlay = overlay;
            //mBaidumap.setOnMarkerClickListener(overlay);
            if(passPoints != null && passPoints.size() > 0) {
                for(int i = 0; i < passPoints.size(); i++) {
                    BitmapDescriptor bitmap = BitmapDescriptorFactory
                            .fromResource(R.drawable.icon_remove_n);
                    if(OrderStatus.N_TO_ONE.equals(type)) {
                        bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_carry_n);
                    }
                    OverlayOptions option = new MarkerOptions()
                            .position(passPoints.get(i))
                            .icon(bitmap);
                    mBaiduMap.addOverlay(option);
                }
            }
            overlay.setData(result.getRouteLines().get(0));
            overlay.addToMap();
            overlay.zoomToSpan();
        }
    }

    //定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (!useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_carry_n);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (!useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.icon_remove_n);
            }
            return null;
        }
    }

    public void destroy() {
        mMapView.onDestroy();
    }

    public MapView getMapView() {
        return mMapView;
    }


}
